<template>
  <div
    class="flex justify-between items-center w-[100vw] h-[60px] bg-[#18181c] border-b-[1px] border-b-[#232324]"
  >
    <div class="flex items-center w-[20vw]">
      <HeaderBtn icon="HomeFilled" name="首页" @click="back" />
      <HeaderBtn icon="QuestionFilled" name="说明" @click="introduce" />
      <HeaderBtn icon="Guide" name="引导" @click="startDriver" />
    </div>

    <div class="text-[#ccc] text-[15px] w-[60vw] text-center">
      {{ props.name || "未命名" }}
    </div>
    <div class="text-[#ccc] text-[15px] w-[20vw] flex justify-end">
      <HeaderBtn icon="View" name="预览" @click="preview" id="driver_preview" />
      <HeaderBtn
        icon="FolderAdd"
        :color="userStore.ifLogin ? 'white' : '#898787'"
        name="保存"
        @click="save"
        id="driver_save"
      />

      <HeaderBtn
        icon="Files"
        name="导入"
        id="driver_import"
        @click="importFileHandle"
      />
      <HeaderBtn
        icon="Download"
        name="导出"
        id="driver_export"
        @click="exportFileHandle"
      />
      <HeaderBtn
        id="driver_codeGen"
        icon="Crop"
        :color="userStore.ifLogin ? 'white' : '#898787'"
        name="生成代码"
        @click="generateCodeHandle"
      />
      <HeaderBtn
        v-if="props.savedId"
        id="driver_publish"
        :color="userStore.ifLogin ? 'white' : '#898787'"
        icon="Position"
        name="发布"
        @click="publishHandle(false)"
      />
      <LoginBox>
        <div class="w-[40px] h-[40px] mr-[10px]">
          <el-dropdown v-if="userStore.ifLogin">
            <img
              class="w-[40px] h-[40px]"
              src="@renderer/assets/images/user_true.png"
            />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="loginOut">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-tooltip
            v-else
            popper-class="my-tooltip cursor-pointer"
            content="点击登录"
            raw-content
          >
            <img
              @click="goLogin"
              class="w-[40px] h-[40px] cursor-pointer"
              src="@renderer/assets/images/user.png"
            />
          </el-tooltip>
        </div>
      </LoginBox>
    </div>
    <CodeDialog
      v-model:value="codeText"
      :editor-placeholder="'请输入'"
      :editor-height="'600'"
      :tab-size="4"
      ref="dialogRef"
      v-if="showDialog"
      @close="closeDialog"
      @toProject="codeToProject(codeText, allComponentsArrs)"
    ></CodeDialog>
    <SaveDialog
      ref="saveDialog"
      :configJson="props.configsJson"
      :layoutJson="props.layout"
      @close="closeSaveDialog"
    />
  </div>
</template>

<script setup lang="ts">
import { Layout } from "@renderer/store/modules/layouts";
import LoginBox from "@renderer/components/topHeader/loginBox.vue";
import HeaderBtn from "./headerBtn/index.vue";
import CodeDialog from "@renderer/components/Codemirror/index.vue";
import SaveDialog from "@renderer/components/saveDialog/index.vue";
import { useUserStore } from "@renderer/store/modules/user";
let userStore = useUserStore();
import {
  getTemplateDetail,
  publishTemplate,
  updataTemplate,
} from "@renderer/api/projectMenu";
import { emitter2 } from "@renderer/utils/event";
import { isEqual } from "@renderer/utils/other";
import { useDriver } from "@renderer/utils/driver";
import "driver.js/dist/driver.css";
import { useRouter } from "vue-router";
const router = useRouter();
const { ipcRenderer } = window;
import { computed, ref, onMounted, onBeforeUnmount } from "vue";
import {
  codeToProject,
  generateCode,
  importFile,
  exportFile,
} from "@renderer/utils/operationCode";
import {
  beforPublicLayout,
  fixLayoutToolong,
} from "@renderer/utils/handleTooLong";

const emit = defineEmits([
  "update:ifPreview",
  "importFile",
  "update:canShortKey",
  "showShortKeyList",
]);
interface PropsType {
  layout: Array<Layout> | undefined;
  configsJson: any;
  savedId: string;
  name?: string;
  ifPreview: boolean;
  canShortKey: boolean;
  currentTemplate: any;
  ifImportFile: boolean;
}
const props = withDefaults(defineProps<PropsType>(), {
  layout: [] as any,
  configsJson: "",
  savedId: "",
  name: "",
  ifPreview: false,
  canShortKey: true,
  currentTemplate: {},
  ifImportFile: false,
});
let initLayout = ref([]);
let initConfig = ref({});

const judgeHandle = () => {
  let flag = judgeEqual();
  // console.log("flag", flag);
  if (!flag) {
    emitter2.emit("ifEqual", false);
    ElMessageBox.confirm("检测到模板有修改，是否保存模板？", {
      cancelButtonText: "继续退出",
      confirmButtonText: "保存",
      closeOnClickModal: false,
      closeOnPressEscape: false,
      showClose: false,
    })
      .then(async () => {
        await save();
      })
      .catch(() => {
        ipcRenderer.send("change-window-size", "closeWin");
        ipcRenderer.send("quitAll");
      });
  } else {
    emitter2.emit("ifEqual", true);
  }
};

onMounted(() => {
  emitter2.on("beforeClose", (arg) => {
    // console.log("arg!!!!!!!!!!!!!", arg);

    judgeHandle();
  });
  setTimeout(() => {
    initData();
  }, 1000);
});
onBeforeUnmount(() => {
  emitter2.removeAllListeners("beforeClose");
});
const initData = () => {
  initLayout.value = JSON.parse(JSON.stringify(props.layout));
  initConfig.value = JSON.parse(JSON.stringify(props.configsJson));
  // console.log("initLayout.value", initLayout.value);
  // console.log("initConfig.value", initConfig.value);
};
const judgeEqual = () => {
  let flag =
    isEqual(initLayout.value, props.layout) &&
    isEqual(initConfig.value, props.configsJson);
  // console.log("flag", flag);
  return flag;
};
const goLogin = () => {
  userStore.toggleShowLogin(true);
};
let saveDialog = ref(null);
let if_preview = computed({
  get() {
    return props.ifPreview;
  },
  set(val) {
    emit("update:ifPreview", val);
  },
});
const showDialog = ref(false);
const dialogRef = ref();
const codeText = ref("");
const introduce = () => {
  emit("showShortKeyList");
};

ipcRenderer.on("openChildWined", (event, arg) => {
  if_preview.value = true;
});

const preview = () => {
  ipcRenderer.removeAllListeners("infoFromMain");
  if (props.layout.length <= 0) {
    ElMessage.warning("当前画布为空");
    return;
  }
  let name = "layout" + GenNonDuplicateID(6);
  if_preview.value = true;
  ipcRenderer.invoke("open-win", {
    url: "/preview?id=" + name,
  });
};
const save = async () => {
  if (!userStore.ifLogin) {
    ElMessage.warning("请先登录才能使用该功能");
    return;
  }
  if (props.layout.length <= 0) {
    ElMessage.warning("当前画布为空");
    return;
  }
  if (props.savedId) {
    let formData = new FormData();
    formData.append("id", props.savedId);
    formData.append("name", props.currentTemplate.name);
    formData.append("isLocalBg", props.currentTemplate.isLocalBg);
    if (props.currentTemplate.isLocalBg == 1) {
      formData.append("bgImgUrl", props.currentTemplate.bgImgUrlShow);
    }
    formData.append("configJson", JSON.stringify(props.configsJson));

    let layoutList = fixLayoutToolong(JSON.parse(JSON.stringify(props.layout)));

    formData.append("layoutJson", JSON.stringify(layoutList));
    updataTemplate(formData).then((res: any) => {
      if (res.code == 200) {
        initData();
        ElMessage.success("保存成功");
        userStore.toggleTemplateChange(false);
        if (props.currentTemplate.pushStatus == 1) {
          ElMessageBox.confirm(
            "检测到模板已经发布，是否同步到资源市场？",
            "已保存成功",
            {
              confirmButtonText: "同步",
              cancelButtonText: "取消",
            }
          ).then(() => {
            publishHandle(true);
          });
        }
      } else {
        ElMessage.error("保存失败，请重试");
      }
    });
  } else {
    saveDialog.value.dialogVisible = true;
    saveDialog.value.init("add");
  }
};

const closeSaveDialog = () => {
  // console.log("closeSaveDialog");
  setTimeout(() => {
    initData();
  }, 1000);
  // initData();
};
const closeDialog = () => {
  showDialog.value = false;
  emit("update:canShortKey", true);
};
const allComponentsArrs = ref([]);
const generateCodeHandle = async () => {
  if (!userStore.ifLogin) {
    ElMessage.warning("请先登录才能使用该功能");
    return;
  }
  if (props.layout.length <= 0) {
    ElMessage.warning("当前画布为空");
    return;
  }
  emit("update:canShortKey", false);
  const { result, allComponentsArrsList } = await generateCode(
    props.layout,
    props.configsJson
  );
  codeText.value = result;
  allComponentsArrs.value = allComponentsArrsList;
  showDialog.value = true;
};

const importFileHandle = async () => {
  let file = await importFile();
  if (file) {
    emit("importFile", file);
  }
};
const exportFileHandle = async () => {
  if (props.layout.length <= 0) {
    ElMessage.warning("当前画布为空");
    return;
  }
  await exportFile(
    props.name || "大屏配置文件",
    props.layout,
    props.configsJson
  );
};

function GenNonDuplicateID(randomLength) {
  return Number(
    Math.random().toString().substr(3, randomLength) + Date.now()
  ).toString(36);
}
const publishHandle = (ifSaved) => {
  if (!userStore.ifLogin) {
    ElMessage.warning("请先登录才能使用该功能");
    return;
  }
  let flag = judgeEqual();
  if (!flag) {
    ElMessage.warning("检测到模板有修改，请先保存模板");
    return;
  }
  if (props.currentTemplate.pushStatus == 1 && !ifSaved) {
    ElMessage.warning("当前模板已发布，请勿重复发布");
    return;
  }

  let formData: any = new FormData();
  formData.append("id", props.savedId);
  formData.append("pushStatus", 1);
  // 去掉数据源信息
  let layoutList = beforPublicLayout(JSON.parse(JSON.stringify(props.layout)));
  formData.append("configJson", JSON.stringify(props.configsJson));
  formData.append("layoutJson", JSON.stringify(layoutList));

  publishTemplate(formData).then((res: any) => {
    if (res.code == 200) {
      ElMessage.success("发布成功");
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  });
};
const back = () => {
  let flag = judgeEqual();
  if (!flag) {
    ElMessageBox.confirm("检测到模板有修改，是否保存模板？", {
      cancelButtonText: "不保存",
      confirmButtonText: "保存",
      showClose: false,
      closeOnClickModal: false,
    })
      .then(async () => {
        await save();
      })
      .catch(() => {
        ipcRenderer.send("close-other");
        router.push("/");
      });
  } else {
    if (props.ifImportFile && !props.savedId) {
      ElMessageBox.confirm("检测到导入模板文件，是否保存？", {
        cancelButtonText: "不保存",
        confirmButtonText: "保存",
        showClose: false,
        closeOnClickModal: false,
      })
        .then(async () => {
          await save();
        })
        .catch(() => {
          ipcRenderer.send("close-other");
          router.push("/");
        });
    } else {
      ipcRenderer.send("close-other");
      router.push("/");
    }
  }
};
const { mydriver } = useDriver();
const startDriver = () => {
  mydriver.value.drive();
};

const loginOut = () => {
  let flag = judgeEqual();
  if (!flag) {
    ElMessageBox.confirm("检测到模板有修改，是否保存模板？", {
      cancelButtonText: "不保存",
      confirmButtonText: "保存",
      closeOnClickModal: false,
      distinguishCancelAndClose: true,
    })
      .then(async () => {
        await save();
      })
      .catch(async (action) => {
        if (action == "cancel") {
          await userStore.loginOut();
        } else if (action == "close") {
        }
      });
  } else {
    ElMessageBox.confirm("确定要退出吗？", {
      cancelButtonText: "取消",
      confirmButtonText: "确定",
      closeOnClickModal: false,
    }).then(async () => {
      await userStore.loginOut();
    });
  }
};
</script>

<style scoped lang="scss"></style>
